package br.com.contaBar.model.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.contaBar.model.domain.HibernateUtil;

public abstract class AbstractDao {
	private Session session;
	private Transaction tx;

	protected void save(Object obj) {
		try {
			startOperation();
			session.save(obj);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	protected void update(Object obj) {
		try {
			startOperation();
			session.update(obj);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
	
	protected void delete(Object obj) {
		try {
			startOperation();
			session.delete(obj);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	protected Object find(Class clazz, Long id) {
		Object obj = null;
		try {
			startOperation();
			obj = session.load(clazz, id);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return obj;
	}

	protected List findAll(Class clazz) {
		List objects = null;
		try {
			startOperation();
			Query query = session.createQuery("from " + clazz.getName());
			objects = query.list();
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return objects;
	}
	
	protected List query(String sql) {
		List objects = null;
		try {
			startOperation();
			Query query = session.createQuery(sql);
			
			objects = query.list();
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return objects;
	}

	protected void startOperation() throws HibernateException {
		session = HibernateUtil.getSession();
		tx = session.beginTransaction();
	}
}